package com.j283_5.wisdom_park.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.j283_5.wisdom_park.common.result.ResultData;
import com.j283_5.wisdom_park.common.utils.FormatTool;
import com.j283_5.wisdom_park.mapper.*;
import com.j283_5.wisdom_park.pojo.*;
import com.j283_5.wisdom_park.service.CarInformationService;
import com.j283_5.wisdom_park.vo.car_management.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author laoda
 * @since 2022-04-28
 */
@Service
@Transactional
public class CarInformationServiceImpl extends ServiceImpl<CarInformationMapper, CarInformation> implements CarInformationService {
    @Resource
    private CarInformationMapper carInformationMapper;
    @Resource
    private VisitorsMapper visitorsMapper;
    @Resource
    private PersonMapper personMapper;
    @Resource
    private PereeMapper pereeMapper;
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private TenementMapper tenementMapper;
    @Resource
    private CarRecordMapper carRecordMapper;

    /**
     * 查询所有车辆信息
     * @param page
     * @param findCarVo
     * @return
     */
    @Override
    public ResultData carInformationList(Page<CarInformation> page, FindCarVo findCarVo) {
        if(page == null){
            page = new Page<>(1,10);
        }
        QueryWrapper<CarInformation> carInformationQueryWrapper = new QueryWrapper<>();
        carInformationQueryWrapper.eq("cinf_state",0);
        if(findCarVo.getCinfMark() != null && findCarVo.getCinfMark().trim().length() > 0){
            carInformationQueryWrapper.like("cinf_mark",findCarVo.getCinfMark());
        }
        if(findCarVo.getCinfClass() != null){
            carInformationQueryWrapper.eq("cinf_class",findCarVo.getCinfClass());
        }
        Page<CarInformation> carInformationPage = carInformationMapper.selectPage(page, carInformationQueryWrapper);

        List<CarInformation> carInformationList = carInformationPage.getRecords();

        ArrayList<Integer> visIdList = new ArrayList<>();
        ArrayList<Integer> personIdList = new ArrayList<>();
        List<Visitors> visitorsList;
        List<Person> personList;
        if(findCarVo.getOwnerPhone() != null){
            //检索访客表
            QueryWrapper<Visitors> visitorsQueryWrapper = new QueryWrapper<>();
            visitorsQueryWrapper.eq("vis_state",0);
            if (findCarVo.getOwnerPhone() != null && findCarVo.getOwnerPhone().trim().length() > 0) {
                visitorsQueryWrapper.like("vis_phone",findCarVo.getOwnerPhone());

            }
            visitorsList = visitorsMapper.selectList(visitorsQueryWrapper);

            if(visitorsList.size() > 0) {
                for (Visitors visitors : visitorsList) {
                    visIdList.add(visitors.getVisId());
                }
            }

            //检索人员表
            QueryWrapper<Person> personQueryWrapper = new QueryWrapper<>();
            personQueryWrapper.eq("person_delete",0);
            if (findCarVo.getOwnerPhone() != null && findCarVo.getOwnerPhone().trim().length() > 0) {
                personQueryWrapper.like("person_phone",findCarVo.getOwnerPhone());

            }
            personList = personMapper.selectList(personQueryWrapper);

            if(personIdList.size() > 0){
                for(Person person : personList){
                    personIdList.add(person.getPersonId());
                }
            }
        }

        ArrayList<CarInformationVo> voArrayList = new ArrayList<>();
        if(carInformationList.size() > 0){
            for(int i=carInformationList.size()-1 ; i>=0 ; i--){
                CarInformation carInformation = carInformationList.get(i);
                CarInformationVo carInformationVo = new CarInformationVo();
                BeanUtils.copyProperties(carInformation,carInformationVo);
                if("visitors".equals(carInformation.getOwnerType())){
                    if(findCarVo.getOwnerPhone() != null && !visIdList.contains(carInformation.getOwnerId())){
                        carInformationList.remove(i);
                    }else{
                        Visitors visitors = visitorsMapper.selectById(carInformation.getOwnerId());
                        carInformationVo.setCinfName(visitors.getVisName());
                        carInformationVo.setCinfPhone(visitors.getVisPhone());
                    }

                }
                if("person".equals(carInformation.getOwnerType())){
                    if(findCarVo.getOwnerPhone() != null && !personIdList.contains(carInformation.getOwnerId())){
                        carInformationList.remove(i);
                    }else{
                        Person person = personMapper.selectById(carInformation.getOwnerId());
                        carInformationVo.setCinfId(person.getPersonId());
                        carInformationVo.setCinfName(person.getPersonName());
                        carInformationVo.setCinfPhone(person.getPersonPhone());
                    }

                }
                voArrayList.add(carInformationVo);
            }

        }
        HashMap<String, Object> map = new HashMap<>();
        if (voArrayList.size() > 0){

            map.put("data",voArrayList);
            map.put("count",carInformationPage.getTotal());
            return ResultData.ok().data(map);
        }else{
            map.put("data",new ArrayList<CarInformationVo>());
            map.put("count",0);
            return ResultData.ok().data(map);
        }



    }


    /**
     * 添加车辆信息
     * @param carVo
     * @return
     */
    @Override
    public ResultData addVisitors(CarVo carVo) {

        CarInformation carInformation = new CarInformation();
        BeanUtils.copyProperties(carVo,carInformation);
        carInformation.setOwnerId(carVo.getOwnerId());
        carInformation.setOwnerType(carVo.getOwnerType());
        carInformation.setCinfStart(new Timestamp(FormatTool.getDate(carVo.getCinfStart(),"yyyy-MM-dd").getTime()));
        carInformation.setCinfEnd(new Timestamp(FormatTool.getDate(carVo.getCinfEnd(),"yyyy-MM-dd").getTime()));


        int i = carInformationMapper.insert(carInformation);

        if (i>0){
            return ResultData.ok().data("添加成功！");
        }else{
            return ResultData.error().data("添加失败！");
        }
    }

    /**
     * 多条件删除
     * @param cinfIdList
     * @return
     */
    @Override
    public ResultData deleteVisitors(ArrayList<Integer> cinfIdList) {
        UpdateWrapper<CarInformation> carInformationServiceUpdateWrapper = new UpdateWrapper<>();
        carInformationServiceUpdateWrapper.in("cinf_id",cinfIdList);
        carInformationServiceUpdateWrapper.set("cinf_state",1);
        int i = carInformationMapper.update(null, carInformationServiceUpdateWrapper);
        if (i>0){
            return ResultData.ok().data("删除成功！");
        }else{
            return ResultData.error().data("删除失败！");
        }
    }

    /**
     * 查询车主信息
     * @param ownerName
     * @param ownerType
     * @return
     */
    @Override
    public ResultData findCarOwner(String ownerName, String ownerType) {
        OwnerVo ownerVo =  null;
        if("visitors".equals(ownerType)) {
            QueryWrapper<Visitors> visitorsQueryWrapper = new QueryWrapper<>();
            visitorsQueryWrapper.eq("vis_name",ownerName);
            Visitors visitors = visitorsMapper.selectOne(visitorsQueryWrapper);
            if(visitors != null){
               // ownerVo = new OwnerVo();
                ownerVo = new OwnerVo(visitors.getVisId(),visitors.getVisName(),visitors.getVisPhone(),
                        (visitors.getVisSex()==1?"男":"女"),"访客",visitors.getVisFace());

            }
        }else if("person".equals(ownerType)){
            QueryWrapper<Person> personQueryWrapper = new QueryWrapper<>();
            personQueryWrapper.eq("person_name",ownerName);
            Person person = personMapper.selectOne(personQueryWrapper);
            if(person != null){
                Peree peree = pereeMapper.selectById(person.getPerId());
                if(peree != null){
                    Room room = roomMapper.selectById(peree.getRoomId());
                    Tenement tenement = tenementMapper.selectById(peree.getTenId());
                    ownerVo = new OwnerVo(person.getPersonId(),person.getPersonName(),person.getPersonPhone(),(person.getPersonSex()==1?"男":"女"),
                            "租户人员",peree.getPerName(),tenement.getTenSerialint(),room.getRoomNo(),person.getPersonPhoto());
                }
            }
        }

        if(ownerVo != null){
            return ResultData.ok().data(ownerVo);
        }else{
            return ResultData.error();
        }

    }

    @Override
    public ResultData findOneCar(Integer cinfId) {
        CarInformation carInformation = carInformationMapper.selectById(cinfId);
        CarVo carVo = new CarVo();
        if(carInformation != null){
            BeanUtils.copyProperties(carInformation,carVo);
            OwnerVo ownerVo = null;
            if("visitors".equals(carInformation.getOwnerType())){
                Visitors visitors = visitorsMapper.selectById(carInformation.getOwnerId());
                if(visitors != null){
                    // ownerVo = new OwnerVo();
                    ownerVo = new OwnerVo(visitors.getVisId(),visitors.getVisName(),visitors.getVisPhone(),
                            (visitors.getVisSex()==1?"男":"女"),"访客",visitors.getVisFace());
                }
            }else if ("person".equals(carInformation.getOwnerType())){
                Person person = personMapper.selectById(carInformation.getOwnerId());
                if(person != null){
                    Peree peree = pereeMapper.selectById(person.getPerId());
                    if(peree != null){
                        Room room = roomMapper.selectById(peree.getRoomId());
                        Tenement tenement = tenementMapper.selectById(peree.getTenId());
                        ownerVo = new OwnerVo(person.getPersonId(),person.getPersonName(),person.getPersonPhone(),(person.getPersonSex()==1?"男":"女"),
                                "租户人员",peree.getPerName(),tenement.getTenSerialint(),room.getRoomNo(),person.getPersonPhoto());
                    }
                }
            }
            if(ownerVo != null){
                carVo.setOwnerVo(ownerVo);
                QueryWrapper<CarRecord> carRecordQueryWrapper = new QueryWrapper<>();
                carRecordQueryWrapper.eq("cinf_id",carInformation.getCinfId());
                carRecordQueryWrapper.orderByDesc("crea_time");
                List<CarRecord> carRecordList = carRecordMapper.selectList(carRecordQueryWrapper);
                if(carRecordList.size()>0){
                    ArrayList<CarRecordVo> carRecordVoList = new ArrayList<>();
                    for(CarRecord carRecord : carRecordList){
                        CarRecordVo carRecordVo = new CarRecordVo(carInformation.getCinfMark(), carInformation.getCinfClass(),
                                (carRecord.getCreaIo() == 0 ? "入场" : "出场"), carRecord.getCreaTime());
                        carRecordVoList.add(carRecordVo);
                    }
                    carVo.setCarRecordVoList(carRecordVoList);
                }
                return ResultData.ok().data(carVo);
            }
        }
        return ResultData.error().message("没有查询到数据");
    }
}
